//
//  AssetTablePicker.m
//
//  Created by Matt Tuzzolo on 2/15/11.
//  Copyright 2011 ELC Technologies. All rights reserved.
//

#import "ELCAssetTablePicker.h"
#import "ELCAssetCell.h"
#import "ELCAsset.h"
#import "ELCAlbumPickerController.h"


@implementation ELCAssetTablePicker

@synthesize parent;
@synthesize selectedAssetsLabel;
@synthesize assetGroup, elcAssets;

-(void)viewDidLoad {
        
	[self.tableView setSeparatorColor:[UIColor clearColor]];
	[self.tableView setAllowsSelection:NO];

    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    self.elcAssets = tempArray;
    [tempArray release];
	
	[self.navigationItem setTitle:NSLocalizedString(@"Loading...", @"")];

	[self performSelectorInBackground:@selector(preparePhotos) withObject:nil];
    
    // Show partial while full list loads
	[self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:.5];
}

-(void)preparePhotos {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	
    NSLog(@"enumerating photos");
    [self.assetGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) 
     {         
         if(result == nil) 
         {
             return;
         }
         
         ELCAsset *elcAsset = [[[ELCAsset alloc] initWithAsset:result] autorelease];
         [elcAsset setParent:self];
         [self.elcAssets addObject:elcAsset];
     }];    
    NSLog(@"done enumerating photos");
	
	[self.tableView reloadData];
	[self.navigationItem setTitle:NSLocalizedString(@"Pick Photos", @"")];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneAction:)] autorelease];
    
    [pool release];

}

- (void)saveSelectPhotos
{
    NSMutableArray *selectedAssetsImages = [[[NSMutableArray alloc] init] autorelease];
    
	for(ELCAsset *elcAsset in self.elcAssets) 
    {		
		if([elcAsset selected]) {
			
			[selectedAssetsImages addObject:elcAsset.asset];
		}
	}
    [(ELCAlbumPickerController*)self.parent saveSelectdPhotoDirectly:selectedAssetsImages];
}

- (void) doneAction:(id)sender {
	
	NSMutableArray *selectedAssetsImages = [[[NSMutableArray alloc] init] autorelease];
	    
	for(ELCAsset *elcAsset in self.elcAssets) 
    {		
		if([elcAsset selected]) {
			
			[selectedAssetsImages addObject:[elcAsset asset]];
		}
	}
    
    [(ELCAlbumPickerController*)self.parent selectedAssets:selectedAssetsImages];
}

#pragma mark UITableViewDataSource Delegate Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ceil([self.assetGroup numberOfAssets] / 4.0)+1;
}

// ugly
-(NSArray*)assetsForIndexPath:(NSIndexPath*)_indexPath {
    
	int index = (_indexPath.row*4);
	int maxIndex = (_indexPath.row*4+3);
    
	// DLog(@"Getting assets for %d to %d with array count %d", index, maxIndex, [assets count]);
    
	if(maxIndex < [self.elcAssets count]) {
        
		return [NSArray arrayWithObjects:[self.elcAssets objectAtIndex:index],
				[self.elcAssets objectAtIndex:index+1],
				[self.elcAssets objectAtIndex:index+2],
				[self.elcAssets objectAtIndex:index+3],
				nil];
	}
    
	else if(maxIndex-1 < [self.elcAssets count]) {
        
		return [NSArray arrayWithObjects:[self.elcAssets objectAtIndex:index],
				[self.elcAssets objectAtIndex:index+1],
				[self.elcAssets objectAtIndex:index+2],
				nil];
	}
    
	else if(maxIndex-2 < [self.elcAssets count]) {
        
		return [NSArray arrayWithObjects:[self.elcAssets objectAtIndex:index],
				[self.elcAssets objectAtIndex:index+1],
				nil];
	}
    
	else if(maxIndex-3 < [self.elcAssets count]) {
        
		return [NSArray arrayWithObject:[self.elcAssets objectAtIndex:index]];
	}
    
	return nil;
}

- (NSString*)getAlbumInfo
{
    if(![self.navigationItem.title isEqualToString:NSLocalizedString(@"Pick Photos", @"")])
    {
        return @"";
    }
    
    NSInteger photoCount = 0, videoCount = 0;
    NSInteger assetCount = [elcAssets count];
    if(assetCount == 0)
    {
        return @"";
    }
    
    for(ELCAsset *elcAsset in self.elcAssets) 
    {
        NSString* assetType = [elcAsset.asset valueForProperty:ALAssetPropertyType];
        if([assetType isEqualToString:ALAssetTypeVideo])
        {
            videoCount++;
        }
        else if([assetType isEqualToString:ALAssetTypePhoto])
        {
            photoCount++;
        }
    }
    
    if(photoCount == 0)
    {
        return [NSString stringWithFormat:NSLocalizedString(@"Show Video Count", ""), videoCount];
    }
    else if(videoCount == 0)
    {
        return [NSString stringWithFormat:NSLocalizedString(@"Show Photo Count", ""), photoCount];
    }
    else
    {
        return [NSString stringWithFormat:NSLocalizedString(@"Show Asset Count", ""), photoCount, videoCount];
    }
    
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";

    ELCAssetCell *cell = (ELCAssetCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    NSInteger cellCount = ceil([self.assetGroup numberOfAssets] / 4.0);
    if (cell == nil) 
    {		        
        cell = [[[ELCAssetCell alloc] initWithAssets:[self assetsForIndexPath:indexPath] reuseIdentifier:CellIdentifier] autorelease];
    }	
    else 
    {		
        [cell setAssets:[self assetsForIndexPath:indexPath]];
    }
    
    if(indexPath.row == cellCount)
    {
        cell.showTitle = [self getAlbumInfo];
    }
    
    return cell;
   
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger cellCount = ceil([self.assetGroup numberOfAssets] / 4.0);
    if(indexPath.row != cellCount)
    {
        return 79;
    }
    else
    {
        return 40;
    }
}

- (int)totalSelectedAssets {
    
    int count = 0;
    
    for(ELCAsset *asset in self.elcAssets) 
    {
		if([asset selected]) 
        {            
            count++;	
		}
	}
    
    return count;
}

- (NSString*)getPickedResult
{
    NSInteger nPhotoCount = 0;
    NSInteger nVideoCount = 0;
    NSInteger selectCount = 0;
    
    for(ELCAsset *elcAsset in self.elcAssets) 
    {		
		if([elcAsset selected]) 
        {
			selectCount += 1;
			NSString* mediaType = [elcAsset.asset valueForProperty:ALAssetPropertyType];
            if([mediaType isEqualToString:ALAssetTypeVideo])
            {
                nVideoCount += 1;
            }
            else
            {
                nPhotoCount += 1;
            }
            
		}
	}

    if(selectCount == 0)
    {
        return NSLocalizedString(@"Pick Photos", @"");
    }
    
    
    if(nPhotoCount == 0)
    {
        return [NSString stringWithFormat:NSLocalizedString(@"Video Picked", ""), nVideoCount];
    }
    else if(nVideoCount == 0)
    {
        return [NSString stringWithFormat:NSLocalizedString(@"Photo Picked", ""), nPhotoCount];
    }
    else
    {
        return [NSString stringWithFormat:NSLocalizedString(@"Asset Picked", ""), selectCount];
    }
    
}

-(void)selectPhotos
{
   [self.navigationItem setTitle:[self getPickedResult]];
}

- (void)dealloc 
{
    [elcAssets release];
    [selectedAssetsLabel release];
    [super dealloc];    
}

@end
